//
//  LLGTabBar.swift
//  Weibo30LLG
//
//  Created by 李龙 on 16/8/8.
//  Copyright © 2016年 lilong. All rights reserved.
//

import UIKit

protocol LLGTabBarDelegate: NSObjectProtocol {

    func didSelectedComposeButton()
}

class LLGTabBar: UITabBar {
    
    weak var llgDelegate: LLGTabBarDelegate?
    
    var composeClosure: (() -> ())?

    // MARK: --懒加载自定义按钮
    private lazy var composeButton: UIButton = {
    
        let button = UIButton()
        
        button.addTarget(self, action: "composeButtonAction", forControlEvents: .TouchUpInside)
        
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Selected)
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
        
        //自适应
        button.sizeToFit()
        
        return button
    }()
    
    // MARK: --点击事件
    @objc private func composeButtonAction() {
    
        composeClosure?()
        
        llgDelegate?.didSelectedComposeButton()
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: --添加UI
    private func setupUI() {
    
        addSubview(composeButton)
        
    }
    
    // MARK: --布局子控件
    override func layoutSubviews() {
        super.layoutSubviews()
        
        //设置按钮中心
        composeButton.centerX = width * 0.5
        composeButton.centerY = height * 0.5
        
        let itemWidth = width / 5
        
        var itemIndex = 0
        
        //UITabBarButton 设置其他按钮位置
        for value in subviews {
        
            if value.isKindOfClass(NSClassFromString("UITabBarButton")!) {
            
                value.width = itemWidth
                value.x = CGFloat(itemIndex) * itemWidth
                
                itemIndex++
                
                if itemIndex == 2 {
                
                    itemIndex++
                }
                
            }
            

        }
        
        
        
    }

}
